﻿using System;
using System.Collections.Generic;

using System.Linq;
using System.Text;
using System.Web;

using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Administration;
using System.Web.UI.WebControls;
using System.Data;
using System.Reflection;
using zevenseas.LifeCycleManagement.Utilities;
using zevenseas.LifeCycleManagement.TimerJobs;

namespace zevenseas.LifeCycleManagement.ApplicationPages
{
    public class OverviewSites : Microsoft.SharePoint.WebControls.LayoutsPageBase
    {
        protected ToolBarButton Mail;
        protected ToolBarButton Lock;
        protected ToolBarButton Delete;
        protected InputFormTextBox TxtUrlSearch;
        protected Label JobStatus;
        protected WebApplicationSelector Selector;
        protected SPGridView gridView;

        private ObjectDataSource dataSource;
        private DataView dataView;      

        protected override void CreateChildControls()
        {
            gridView.ID = "gridView";
            gridView.AutoGenerateColumns = false;
            gridView.AlternatingRowStyle.BackColor = System.Drawing.Color.WhiteSmoke;
            
            // Set EventHandler for setting the filter icon
            gridView.RowDataBound += new GridViewRowEventHandler(m_oGridView_RowDataBound);

           // gridView.Sorting += new GridViewSortEventHandler(gridView_Sorting);

            // Create the datasource object
            dataSource = new ObjectDataSource();

            string strTypeName = "zevenseas.LifeCycleManagement.ApplicationPages.OverviewSites,";
            strTypeName += Assembly.GetExecutingAssembly().FullName;

            dataSource.TypeName = strTypeName;
            dataSource.SelectMethod = "GetSites";
            dataSource.ID = "UnusedSitesDataSource";

            dataView = (DataView)dataSource.Select();

            if (TxtUrlSearch != null)
            {
                if (!string.IsNullOrEmpty(TxtUrlSearch.Text.ToString()))
                {
                    dataView.RowFilter = "Url LIKE '*" + this.TxtUrlSearch.Text + "*'";
                }
            }


            HttpRequest oRequest = HttpContext.Current.Request;
            if ((oRequest.Form["__CALLBACKID"] == null) ||
                (oRequest.Form["__CALLBACKPARAM"] == null) ||
                (!oRequest.Form["__CALLBACKID"].EndsWith("gridView")))
            {
                if (null != ViewState["FilterExpression"])
                {
                    dataSource.FilterExpression = (string)ViewState["FilterExpression"];
                }
            }

            Controls.Add(dataSource);
            gridView.DataSource = dataView;         

            base.CreateChildControls();
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            if (!Utilities.Utilities.IsEmailConfigured())
            {
                Mail.Visible = false;
            }
        }

        protected override void OnLoadComplete(EventArgs e)
        {
            try
            {
                SPWebApplication local = Selector.CurrentItem;
                

                SiteLifeCycleGatherTimerjob gatherJob = local.JobDefinitions.GetValue<SiteLifeCycleGatherTimerjob>("LCMGatherJob_Manual");
                if (gatherJob != null)
                {
                    this.JobStatus.Text = "Statistics Gathering Timer Job is running and processed " + gatherJob.PSitesProcessed.ToString() + " sites so far"; ;
                }
                else
                {
                    this.JobStatus.Text = "Statistics Gathering Timer Job is not running";
                    GatherTimerJobStatus status = local.GetChild<GatherTimerJobStatus>("GatherTimerJobStatus");
                    if (status != null)
                    {
                        this.JobStatus.Text += "<BR>Statistics Gathering Timer Job last ran at " + status.LastRunTime.ToShortDateString();
                    }
                }

                SiteLifeCycleActionTimerjob actionJob = local.JobDefinitions.GetValue<SiteLifeCycleActionTimerjob>("LCMActionJob_Manual");
                if (actionJob != null)
                {
                    this.JobStatus.Text += "<BR>Maintenance Timer Job is not running is running and processed " + actionJob.PSitesProcessed.ToString() + " sites so far"; ;
                }
                else
                {
                    this.JobStatus.Text += "<BR>Maintenance Timer Job is not running at the moment";
                    ActionTimerJobStatus status = local.GetChild<ActionTimerJobStatus>("ActionTimerJobStatus");
                    if (status != null)
                    {
                        this.JobStatus.Text += "<BR>Maintenance Timer Job last ran at " + status.LastRunTime.ToShortDateString();
                    }
                }

            }
            catch
            {
            }
            base.OnLoadComplete(e);
        }

        protected override void OnPreRender(System.EventArgs e)
        {

            ViewState["FilterExpression"] = dataSource.FilterExpression;
            base.OnPreRender(e);

        }

        // --------------------

        protected override void Render(System.Web.UI.HtmlTextWriter writer)
        {
            //gridView.DataBind();
            BindData();
            base.Render(writer);
        }

        // --------------------

        void m_oGridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if ((null != sender) && (e.Row.RowType == DataControlRowType.Header))
            {
                string strFilteredColumn = ((SPGridView)sender).FilterFieldName;
                SetGridViewFilterIcon(gridView, strFilteredColumn, e.Row);
            }
        }

        // --------------------

        public void SetGridViewFilterIcon(SPGridView gridView, string strColumn, GridViewRow row)
        {
            if ((false == string.IsNullOrEmpty(strColumn)) && (null != row))
            {
                // Show icon on filtered column
                for (int iIndex = 0; iIndex < gridView.Columns.Count; iIndex++)
                {
                    DataControlField oField = gridView.Columns[iIndex];

                    if (oField.HeaderText == strColumn)
                    {
                        Image filterIcon = new Image();
                        filterIcon.ImageUrl = "/_layouts/images/ewr093.gif";
                        filterIcon.ImageAlign = ImageAlign.Left;
                        filterIcon.Style[System.Web.UI.HtmlTextWriterStyle.MarginTop] = "2px";
                        filterIcon.ID = "FilterIcon";

                        Panel panel = new Panel();
                        panel.Controls.Add(filterIcon);

                        row.Cells[iIndex].Controls.Add(panel);

                        break;
                    }
                }
            }
        }

        public void BindData()
        {
            if (dataView != null)
            {
                dataView = (DataView)dataSource.Select();

                if (Selector != null)
                {
                    dataView.RowFilter = "WebApplication LIKE '*" + Selector.CurrentItem.Name + "*'";
                }

                if (TxtUrlSearch != null)
                {
                    if (!string.IsNullOrEmpty(TxtUrlSearch.Text.ToString()))
                    {
                        dataView.RowFilter = "AND Url LIKE '*" + TxtUrlSearch.Text + "*'";
                    }
                }

                gridView.DataSource = dataView;
                gridView.DataBind();
            }
        }

      

        public DataTable GetSites()
        {
            DataTable sitesDataTable = new DataTable();

            if (Utilities.Utilities.CheckIfLCMExists())
            {
                SPList unusedSitesList = SPContext.Current.Web.Webs["LCM"].Lists["UnusedSites"];

                SPQuery query = new SPQuery();
                // query.Query = "<Where><Eq><FieldRef Name='WebApplication' /><Value Type='Text'>" + webApplicationName + "</Value></Eq></Where><OrderBy />";
                query.Query = "<OrderBy><FieldRef Name='ID' Ascending='True' /></OrderBy>";
                sitesDataTable = unusedSitesList.GetItems(query).GetDataTable();
                
            }
            return sitesDataTable;
        }

        public void RefreshStatsClick(object sender, EventArgs e)
        { 
        
        }

        public void SearchLinkClick(object sender, EventArgs e)
        {
        }

        public void GatherLink(object sender, EventArgs e)
        {
            SPWebApplication local = Selector.CurrentItem;
            if (local.JobDefinitions.GetValue<SiteLifeCycleGatherTimerjob>("LCMGatherJob_Manual") == null)
            {
                SiteLifeCycleGatherTimerjob siteLifeCycleGatherJob = new SiteLifeCycleGatherTimerjob("LCMGatherJob_Manual", local, null, SPJobLockType.Job);
                SPOneTimeSchedule schedule = new SPOneTimeSchedule(DateTime.Now);
                siteLifeCycleGatherJob.Schedule = schedule;
                siteLifeCycleGatherJob.Name = "LCMGatherJob_Manual";
                siteLifeCycleGatherJob.Title = "LCMGatherJob_Manual";                
                siteLifeCycleGatherJob.Update();                
            }
        }

        public void ActionLink(object sender, EventArgs e)
        {
            SPWebApplication local = Selector.CurrentItem;
            if (local.JobDefinitions.GetValue<SiteLifeCycleGatherTimerjob>("LCMActionJob_Manual") == null)
            {
                SiteLifeCycleActionTimerjob siteLifeCycleActionTimerjob = new SiteLifeCycleActionTimerjob("LCMActionJob_Manual", local, null, SPJobLockType.Job);
                SPOneTimeSchedule schedule = new SPOneTimeSchedule(DateTime.Now);
                siteLifeCycleActionTimerjob.Schedule = schedule;
                siteLifeCycleActionTimerjob.Name = "LCMActionJob_Manual";
                siteLifeCycleActionTimerjob.Title = "LCMActionJob_Manual";
                siteLifeCycleActionTimerjob.Update();
            }
        }

        public void LockLink(object sender, EventArgs e)
        {
            if (((base.Request != null) && (base.Request["ctl00$PlaceHolderMain$HiddenSiteSelections"] != null)) && !string.IsNullOrEmpty(base.Request["ctl00$PlaceHolderMain$HiddenSiteSelections"]))
            {
                string[] urls = base.Request["ctl00$PlaceHolderMain$HiddenSiteSelections"].ToString().Split(new Char[] { '#' });

                foreach (string url in urls)
                {
                    if (!string.IsNullOrEmpty(url))
                    {
                        bool locked = false;
                        try
                        {
                            SPSiteAdministration siteAdmin = new SPSiteAdministration(url);
                            siteAdmin.WriteLocked = true;
                            siteAdmin.Dispose();
                            locked = true;
                        }
                        catch (Exception error)
                        {
                            SPUtility.TransferToErrorPage(error.Message.ToString());
                        }

                        if (locked)
                        {
                            SPListItem item = Utilities.Utilities.GetAssociatedListItem(url);
                            item["Locked"] = true;
                            item["LockedAt"] = System.DateTime.Today;
                            item.Update();
                        }
                    }
                }
            }           
        }

        public void MailLink(object sender, EventArgs e)
        {
            if (((base.Request != null) && (base.Request["ctl00$PlaceHolderMain$HiddenSiteSelections"] != null)) && !string.IsNullOrEmpty(base.Request["ctl00$PlaceHolderMain$HiddenSiteSelections"]))
            {
                string[] urls = base.Request["ctl00$PlaceHolderMain$HiddenSiteSelections"].ToString().Split(new Char[] { '#' });

                foreach (string url in urls)
                {
                    if (!string.IsNullOrEmpty(url))
                    {
                        SPListItem item = Utilities.Utilities.GetAssociatedListItem(url);
                        SPWebApplication webApplication = Selector.CurrentItem;
                        SiteLifeCycleSettings settings = webApplication.GetChild<SiteLifeCycleSettings>("SiteLifeCycleSettings");
                        
                        string emailBody = string.Empty;
                        string emailSubject = string.Empty;

                        if (settings != null)
                        {  
                            emailBody = settings.emailBody.ToString();
                            emailSubject = settings.emailSubject.ToString();
                        }

                        string emailTo = item["OwnerEmailAddress"].ToString();
                        ////string emailSubject = item["Title"] + " at : " + url + Utilities.Utilities.GetWebProperty("mailSubject", SPContext.Current.Web.Properties);
                        ////string emailBody = Utilities.Utilities.GetWebProperty("mailContent", SPContext.Current.Web.Properties);

                        if (SPUtility.SendEmail(item.ParentList.ParentWeb, false, false, emailTo, emailSubject, emailBody))
                        {
                            //updating list if email is successfully sent
                            item["MailedAt"] = System.DateTime.Today;
                            item["Mailed"] = true;
                            item.Update();
                        }
                    }
                }
            }
        }

        public void DeleteLink(object sender, EventArgs e)
        {
            if (((base.Request != null) && (base.Request["ctl00$PlaceHolderMain$HiddenSiteSelections"] != null)) && !string.IsNullOrEmpty(base.Request["ctl00$PlaceHolderMain$HiddenSiteSelections"]))
            {
                string[] urls = base.Request["ctl00$PlaceHolderMain$HiddenSiteSelections"].ToString().Split(new Char[] { '#' });

                foreach (string url in urls)
                {
                    if (!string.IsNullOrEmpty(url))
                    {
                        bool siteIsDeleted = false;

                        try
                        {
                            SPSiteAdministration siteAdmin = new SPSiteAdministration(url);
                            siteAdmin.Delete();
                            siteAdmin.Dispose();
                            siteIsDeleted = true;
                        }

                        catch (Exception error)
                        {
                            SPUtility.TransferToErrorPage(error.Message.ToString());
                        }

                        if (siteIsDeleted)
                        {
                            SPListItem item = Utilities.Utilities.GetAssociatedListItem(url);
                            item["Deleted"] = true;
                            item["DeletedAt"] = System.DateTime.Today;
                            item.Update();

                        }
                    }
                }
            }
        }
    }
}
